<?php include "classes.inc" ?>
<?php include "constants.inc" ?>
<?php session_start(); ?>
<?php

$folder = "default";
$status = 'failure';
$error = "";

if ( isset($_SESSION['user']) ) {
      $user = $_SESSION['user'];
      $folder = $user->user_id;
}

$name = trim($_POST['tournamentName']);
$ref = trim($_POST['ref']);

if ( !empty($name) && strnatcasecmp($name, '') != 0 && !empty($ref) && strnatcasecmp($ref, '?') != 0 ) {
    
    mysql_connect(DB_SERVER, DB_USER, DB_PWD);
    mysql_select_db(DB_CATALOG);
    $query = sprintf("select upload_id from uploaded_tournament where name = '%s'", $name);
    $result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_assoc($result);
        $upload_id = $row['upload_id'];
        $query = sprintf("update uploaded_tournament set date = CURDATE(), ref = '%s' 
            where upload_id = %u", $ref, $upload_id);
        mysql_query($query);
    } else {
        $query = sprintf("insert into uploaded_tournament (name, date, ref, user_id) values ('%s',CURDATE(),'%s',%u)",
            $name, $ref, $user->user_id);
        mysql_query($query);
    }

    $filename = basename($_FILES['uploadTestFile']['name']);
    if ( !empty($filename) ) {
        // fake delay of 3 seconds
        sleep(3);
        $uploadDirectory = dirname(__FILE__).'/upload/'.$folder;
        if (!file_exists($uploadDirectory)) {
            mkdir($uploadDirectory);
        }
        $newname = $uploadDirectory."/".$filename;
        if (move_uploaded_file($_FILES['uploadTestFile']['tmp_name'],$newname)) {
            $status = 'success';
        } else {
            $error = "Kon file ".$filename." niet verplaatsen.";
        }    
    } else {
         //$error = "Geen bestand gevonden.";
         // it's ok not to upload a file since it might be used to change tournament info
         $status = 'success';
    }
    
} else {
    $error = "Naam en referentiebestand moeten ingevuld zijn.";
}

// this is what we are returning.  we can do whatever we want to make this
// array. 
$ar = array(
    'details' => $_FILES['uploadTestFile'],
    'status' => $status
);

// encode our array, and dump it back to the Deferred that called us to upload this file
$foo = "{'error':'".$error."','status':'".$status."',details: {name:'".
    $_FILES['uploadTestFile']['name'].
    "',size:".
    $_FILES['uploadTestFile']['size'].
    "}}";

// yeah, seems you have to wrap iframeIO stuff in textareas?
?><textarea><?php
print $foo; 
?></textarea>

